package com.example.user_manage.service;

import com.example.user_manage.entity.User;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@AllArgsConstructor
public class SecurityService implements UserDetailsService {

    /**
     * 用户服务对象
     */
    final UserService userService;

    /**
     * 用户登录
     * @param username 用户名（对应User对象的LoginAct登录账号）
     * @return 用户细节对象
     * @throws UsernameNotFoundException 找不到用户异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户登录开始");
            User user = userService.selectUserByLoginAct(username);
            if(user == null) {
                log.error("该用户不存在");
                throw new UsernameNotFoundException("该用户不存在");
            }else {
                //获取该用户的角色权限列表
                user.setRoleList(userService.selectRolesByUserId(user.getId()));
                return user;
            }
    }
}
